import axios,{AxiosResponse,Method,InternalAxiosRequestConfig}from "axios";
import {message} from 'antd';
import store from '../redux'
axios.defaults.baseURL = 'http://119.3.122.213:8090/api/private/v1/';
axios.defaults.timeout = 60000;
// 请求拦截
axios.interceptors.request.use((config:InternalAxiosRequestConfig):InternalAxiosRequestConfig=>{
    // 提供token令牌
    let token = store.getState().tokenReducer.token;
    config.headers['Authorization'] = token;
    return config
},(err:any)=>{
    Promise.reject(err)
})

// 响应拦截
axios.interceptors.response.use((res:AxiosResponse)=>{
    if(res.data.meta.status===200 || res.data.meta.status===201 || res.data.meta.status===204){
        message.success(res.data.meta.msg)
    }else if(res.data.meta.status===400 || res.data.meta.status===401){
        message.error(res.data.meta.msg);
        localStorage.removeItem("token");
        store.dispatch({
            type:"SET_TOKEN",
            token:null
        })
        // 跳转到登录页面
        window.location.hash='/login'
    }else{
        message.error(res.data.meta.msg)
    }
    return res
},(err:any)=>{
    Promise.reject(err)
})  

let http = (url:string,method:Method='GET',data:DataType | null={},headers:any={
    'content-type':"application/json"
}):Promise<any>=>{ 
    return axios({
        url,
        method,
        // post请求参数
        data:method!=='GET'?data:null,
        params:method==='GET'?data:null,
        headers
    })
}


export default http;